package me.wangqu.weiyouqu.web.rest;

import com.codahale.metrics.annotation.Timed;
import me.wangqu.weiyouqu.domain.ViewPager;
import me.wangqu.weiyouqu.repository.ViewPagerRepository;
import me.wangqu.weiyouqu.security.AuthoritiesConstants;
import me.wangqu.weiyouqu.web.rest.util.HeaderUtil;
import me.wangqu.weiyouqu.web.rest.util.PaginationUtil;
import me.wangqu.weiyouqu.web.rest.dto.ViewPagerDTO;
import me.wangqu.weiyouqu.web.rest.mapper.ViewPagerMapper;
import me.wangqu.weiyouqu.web.rest.util.constant.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing ViewPager.
 */
@RestController
@RequestMapping("/api")
public class ViewPagerResource {

    private final Logger log = LoggerFactory.getLogger(ViewPagerResource.class);

    @Inject
    private ViewPagerRepository viewPagerRepository;

    @Inject
    private ViewPagerMapper viewPagerMapper;

    /**
     * 获取我的页面头部轮播广告图片
     * @param pageable
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping(value = "/view-pagers/type/me-header",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<List<ViewPager>> getMeHeaderViewPagers(Pageable pageable)
            throws URISyntaxException {
        log.debug("REST request to get a page of me header ViewPagers");
        Page<ViewPager> page = viewPagerRepository.findByType(Constant.VIEWPAGER_TYPE_ME_HEADER, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/view-pagers");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * POST  /view-pagers : Create a new viewPager.
     *
     * @param viewPagerDTO the viewPagerDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new viewPagerDTO, or with status 400 (Bad Request) if the viewPager has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/view-pagers",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ViewPagerDTO> createViewPager(@Valid @RequestBody ViewPagerDTO viewPagerDTO) throws URISyntaxException {
        log.debug("REST request to save ViewPager : {}", viewPagerDTO);
        if (viewPagerDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("viewPager", "idexists", "A new viewPager cannot already have an ID")).body(null);
        }
        ViewPager viewPager = viewPagerMapper.viewPagerDTOToViewPager(viewPagerDTO);
        viewPager = viewPagerRepository.save(viewPager);
        ViewPagerDTO result = viewPagerMapper.viewPagerToViewPagerDTO(viewPager);
        return ResponseEntity.created(new URI("/api/view-pagers/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("viewPager", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /view-pagers : Updates an existing viewPager.
     *
     * @param viewPagerDTO the viewPagerDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated viewPagerDTO,
     * or with status 400 (Bad Request) if the viewPagerDTO is not valid,
     * or with status 500 (Internal Server Error) if the viewPagerDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/view-pagers",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ViewPagerDTO> updateViewPager(@Valid @RequestBody ViewPagerDTO viewPagerDTO) throws URISyntaxException {
        log.debug("REST request to update ViewPager : {}", viewPagerDTO);
        if (viewPagerDTO.getId() == null) {
            return createViewPager(viewPagerDTO);
        }
        ViewPager viewPager = viewPagerMapper.viewPagerDTOToViewPager(viewPagerDTO);
        viewPager = viewPagerRepository.save(viewPager);
        ViewPagerDTO result = viewPagerMapper.viewPagerToViewPagerDTO(viewPager);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("viewPager", viewPagerDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /view-pagers : get all the viewPagers.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of viewPagers in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value = "/view-pagers",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<ViewPagerDTO>> getAllViewPagers(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of ViewPagers");
        Page<ViewPager> page = viewPagerRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/view-pagers");
        return new ResponseEntity<>(viewPagerMapper.viewPagersToViewPagerDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * GET  /view-pagers/:id : get the "id" viewPager.
     *
     * @param id the id of the viewPagerDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the viewPagerDTO, or with status 404 (Not Found)
     */
    @RequestMapping(value = "/view-pagers/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ViewPagerDTO> getViewPager(@PathVariable Long id) {
        log.debug("REST request to get ViewPager : {}", id);
        ViewPager viewPager = viewPagerRepository.findOne(id);
        ViewPagerDTO viewPagerDTO = viewPagerMapper.viewPagerToViewPagerDTO(viewPager);
        return Optional.ofNullable(viewPagerDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /view-pagers/:id : delete the "id" viewPager.
     *
     * @param id the id of the viewPagerDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @RequestMapping(value = "/view-pagers/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteViewPager(@PathVariable Long id) {
        log.debug("REST request to delete ViewPager : {}", id);
        viewPagerRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("viewPager", id.toString())).build();
    }

}
